<template>
  <div>
    <Form ref="form" :model="paramAdd" :label-width="120" :show-message="false" style="max-width: 80%;text-align: left">

      <FormItem label="选品来源" prop="platform" required>
        <RadioGroup v-model="paramAdd.platform">
          <Radio label="1688">1688</Radio>
          <Radio label="aliexpress">Aliexpress</Radio>
        </RadioGroup>
      </FormItem>

      <FormItem label="选品链接" prop="orignalUrl" >
        <Input  type="text" v-model="paramAdd.orignalUrl" @on-change="autoParamOrignalUrl" placeholder="https://www.1688.com/****"></Input>
        <Checkbox v-model="paramAdd.isCaijiURL" @on-change="autoCaijiUrl">同为采集地址</Checkbox>
        <Checkbox v-model="paramAdd.urlIsSource" @on-change="autoURLSource">同为货源地址</Checkbox>
      </FormItem>


      <FormItem label="竞品售价(美元)" prop="competitorPriceUS" v-if="isFromAliexpress" :required="isFromAliexpress">
        <Input type="number" v-model="paramAdd.competitorPriceUS" prefix="logo-usd"></Input>
      </FormItem>

      <FormItem label="采集链接" prop="url" required >
        <Input type="text" v-model.trim="paramAdd.url" border @on-change="autoParamUrl" placeholder="https://www.1688.com/****"
               ></Input>
        <p class="base_key">我们将会采集该链接的产品图片+色卡+产品属性等信息</p>

      </FormItem>

      <FormItem label="货源" prop="otherSourceUrls">
        <Button type="primary" size="small" @click="addOtherSourceUrl()">+添加货源</Button>
        <template v-if="paramAdd.otherSourceUrls != null">
          <Row v-for="(item, index) in paramAdd.otherSourceUrls" :key="index" style="margin-top: 10px;">
            <i-col :span="22">
              <Input type="url"  v-model.trim="paramAdd.otherSourceUrls[index]" @on-change="autoParamOtherSource($event,index)"
                     placeholder="https://www.***.com/****"  ></Input>
            </i-col>
            <i-col :span="2">
              <Button type="error" style="margin-left: 10px;" @click="deleteOtherSourceUrl(index)">删除</Button>
            </i-col>
          </Row>
        </template>
      </FormItem>


      <FormItem label="采集分类" prop="categories" required>
        <Cascader v-model="paramAdd.categories" :data="categoryTreeData" change-on-select placeholder="请选择采集分类"></Cascader>
      </FormItem>

      <FormItem label="采集批次" prop="batch" required>
        <Input type="text" v-model.trim="paramAdd.batch" placeholder="例如: 220318">
          <span slot="prepend">{{getStationShortName(station.code)}}</span>
        </Input>
        <p class="base_key">同批次号的产品, 会同一批进行采集</p>
      </FormItem>
      <FormItem label="采集理由" prop="collectReason" required>
        <RadioGroup v-model="paramAdd.collectReason">
          <Radio v-for="(item, index) in reasons" :key="index" :label="item" border>{{item}}</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem>
        <Button type="success" @click="saveSelectedProduct()">提交</Button>
        <Button style="margin-left: 8px" @click="resetForm()">清空</Button>
      </FormItem>
    </Form>

  </div>
</template>

<script>
import productAddData from "./js/add/productAddData";
import {queryMongoCategories} from "./js/product/productFuns";
import {isEmpty, isNotEmpty} from "../js/commonUtils";

export default {
  name: "ProductAdd",
  data() {
    return {
      station: this.$store.getters.siteInfo,
      stations: [
        {name: "TIY", code: 10},
        {name: "W05", code: 13},
      ],
      paramAdd: productAddData.tParam.paramAdd,
      categoryTreeData: [],
      reasons: ["顾客找品", "平台爆款", "优质货源跟随上新", "自主选品(根据找品/节日)", "普通上新"]
    }
  },
  computed: {
    isFromAliexpress() {
      return this.paramAdd.platform == 'aliexpress';
    }
  },
  methods:{
    autoCaijiUrl(isCaiji){
      if(isEmpty(this.paramAdd.orignalUrl)) {
        return;
      }
      if (isCaiji){
        this.paramAdd.url = this.paramAdd.orignalUrl;
      }else{
        if (this.paramAdd.url === this.paramAdd.orignalUrl){
          this.paramAdd.url = "";
        }
      }
    },
    autoURLSource(isSource){
      if(isEmpty(this.paramAdd.orignalUrl)) {
        return;
      }
      var index = this.paramAdd.otherSourceUrls.indexOf(this.paramAdd.orignalUrl);
      if (isSource){
        if (index<0)
        this.paramAdd.otherSourceUrls.push(this.paramAdd.orignalUrl);
      }else{
        this.paramAdd.otherSourceUrls.splice(index,1);
      }
    },
    addOtherSourceUrl() {
      this.paramAdd.otherSourceUrls.push("");
    },
    deleteOtherSourceUrl(index) {
      this.paramAdd.otherSourceUrls.splice(index, 1);
    },
    getStationShortName(code) {
      let station = this.stations.find(station => station.code == code);
      if(station == null) {
        return this.station.name;
      }
      return station.name;
    },
    saveSelectedProduct() {
      this.$refs.form.validate(valid => {
        if(valid) {
          let params = this.paramAdd;
          this.$Spin.show();
          this.$apiImpProduct.saveSelectedProduct(params).then(response => {
            this.$Spin.hide();
            if(response.success) {
              this.$Message.success({content: "保存成功！", duration: 4});
              this.initPageInfo();
            }else{
              console.error(response);
              this.$Message.error("保存失败："+response.errorMessage);
            }
          }).catch(() => {
            this.$Spin.hide();
            this.$Message.error("数据提交失败！");
          })
        }else{
          if(isEmpty(this.paramAdd.collectReason)) {
            this.$Message.error({content: "请选择采集理由", duration: 3})
          }
          console.error("表单验证失败！");
        }
      })
    },
    resetForm() {
      this.initPageInfo();
    },
    initPageInfo() {
      productAddData.tParam.paramAdd.platform = "1688";
      productAddData.tParam.paramAdd.competitorPriceUS = null;
      productAddData.tParam.paramAdd.orignalUrl = "";
      productAddData.tParam.paramAdd.isCaijiURL = false;
      productAddData.tParam.paramAdd.url = "";
      productAddData.tParam.paramAdd.urlIsSource = false;
      productAddData.tParam.paramAdd.otherSourceUrls.splice(0);
      productAddData.tParam.paramAdd.categories.splice(0);
      productAddData.tParam.paramAdd.batch = "";
      this.$refs.form.resetFields();
    },
    autoParamOrignalUrl(event) {
      var value = event.target.value;
      value = this.autoURL(value);
      if (value) {
        this.$nextTick(() => {
          this.paramAdd.orignalUrl = value;
          this.autoCaijiUrl(this.paramAdd.isCaijiURL);
          this.autoURLSource(this.paramAdd.urlIsSource);
        });
      }
    },
    autoParamUrl(event){
     var value = event.target.value;
     value = this.autoURL(value);
      if (value) {
        this.$nextTick(() => {
          this.paramAdd.url = value;
        });
      }
    },
    autoParamOtherSource(event,index){
      var value = event.target.value;
      value = this.autoURL(value);
      if (value) {
        this.$nextTick(() => {
          this.$set(this.paramAdd.otherSourceUrls, index, value)
        });
      }
    },

    autoURL(href){
      // console.log("before href: "+href);
      var pureHref = "";
      let endIndex = href.indexOf("?");
      if (endIndex===-1){
        pureHref = href;
      }else{
        pureHref = href.substring(0,endIndex);
      }
      pureHref = pureHref.replace( /(aliexpress.[a-z]*\/)/,'aliexpress.com/');
      pureHref = pureHref.replace( /([a-z\.]*aliexpress)/,'www.aliexpress');
      pureHref = pureHref.replace( /(detail.1688.[a-z]*\/)/,'detail.1688.com/');
      // pureHref = pureHref.replace(/([a-z\.]*detail.1688)/,'www.detail.1688')
      // console.log("after href: "+pureHref);
      return pureHref;

    }
  },
  mounted() {
    this.initPageInfo();
    queryMongoCategories(this, this.categoryTreeData);
  },
}
</script>

<style scoped lang="less">
@import (once,optional)  "../css/base.less";

</style>
